Cesium.Ion.defaultAccessToken =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI2MmEwNGQwMS1jYjFhLTRkODQtYWYyYS1iYTFiODJmYTEwMzciLCJpZCI6MzIwNDksInNjb3BlcyI6WyJhc3IiLCJnYyJdLCJpYXQiOjE1OTY0MjA2NjN9.3WtUOG_UaUNQucOGTH9o0B7HS70yT3rxSsaVKYFXt0g";
const viewer = new Cesium.Viewer("cesiumContainer", {
  animation: false,
  timeline: false,
  fullscreenButton: false,
  geocoder: false,
  baseLayerPicker: false,
  infoBox: true,
  navigationInstructionsInitiallyVisible: false,
  homeButton: false,
  sceneModePicker: false,
  navigationHelpButton: false,
  terrainProvider: new Cesium.CesiumTerrainProvider({
    url: "http://data.marsgis.cn/terrain",
  }),
  imageryProvider: new Cesium.ArcGisMapServerImageryProvider({
    url:
      "http://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer",
    enablePickFeatures: false,
  }),
});
viewer.scene.globe.depthTestAgainstTerrain = true;
//去除版权信息
viewer._cesiumWidget._creditContainer.style.display = "none";
const tileset = new Cesium.Cesium3DTileset({
  url: "../data/NMCF_JSON/tileset.json",
});
tileset.readyPromise
  .then(function (tileset) {
    changeHeight(1125);
    viewer.scene.primitives.add(tileset);
    viewer.zoomTo(
      tileset,
      new Cesium.HeadingPitchRange(
        0.0,
        -0.5,
        tileset.boundingSphere.radius * 1.0
      )
    );
    loadDevice();
  })
  .otherwise(function (error) {
    console.log(error);
  });

function changeHeight(height) {
  height = Number(height);
  if (isNaN(height)) {
    return;
  }
  var cartographic = Cesium.Cartographic.fromCartesian(
    tileset.boundingSphere.center
  );
  var surface = Cesium.Cartesian3.fromRadians(
    cartographic.longitude,
    cartographic.latitude,
    cartographic.height
  );
  var offset = Cesium.Cartesian3.fromRadians(
    cartographic.longitude,
    cartographic.latitude,
    height
  );
  var translation = Cesium.Cartesian3.subtract(
    offset,
    surface,
    new Cesium.Cartesian3()
  );
  tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
}

const [baseUrl, gpsUrl, jrxUrl, kswUrl, nbwyUrl, yljUrl] = [
  "http://58.56.27.78:8888/HLWKK/GetHLSBXX", //"api/realinfo.json", //"api/baseinfo.json",
  "http://58.56.27.78:8888/HLWKK/GetHLGPSData", //"api/gps.json",
  "http://58.56.27.78:8888/HLWKK/GetHLJRXData", //"api/jrx.json",
  "http://58.56.27.78:8888/HLWKK/GetHLKSWData", //"api/ksw.json",
  "http://58.56.27.78:8888/HLWKK/GetHLNBWYData", //"api/nbwy.json",
  "http://58.56.27.78:8888/HLWKK/GetHLYLData", //"api/ylj.json",
];
function loadDevice() {
  fetch(baseUrl, {
    method: "GET",
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Content-Type": "text/plain",
    },
  }).then(
    (res) => {
      res.json().then((data) => {
        const info = data.JCSBXX;
        for (let i = 0; i < info.length; i++) {
          const { jcsbSbbh, jd, wd, gc } = info[i];
          const position = new Cesium.Cartographic(
            (Number(jd) * Math.PI) / 180,
            (Number(wd) * Math.PI) / 180
          );
          if (jcsbSbbh.indexOf("JRX") > -1) {
            loadJRX(position, info[i]);
          } else if (jcsbSbbh.indexOf("GPS") > -1) {
            loadGPS(position, info[i]);
          } else if (jcsbSbbh.indexOf("SWJ") > -1) {
            loadKSW(position, info[i]);
          } else if (jcsbSbbh.indexOf("CXY") > -1) {
            loadNBWY(position, info[i]);
          } else if (jcsbSbbh.indexOf("YLJ") > -1) {
            loadYLJ(position, info[i]);
          }
        }
      });
    },
    (err) => {
      console.log(err, "===err");
    }
  );
}

function loadJRX(position, data) {
  const { jcsbSbbh, jd, wd, gc } = data;
  fetch(`${jrxUrl}?jrxSbbh=${jcsbSbbh}`).then((res) => {
    res.json().then((jrxData) => {
      const jrxArray = jrxData.JRX;
      const info = jrxArray.reduce((pre, curr) => {
        pre += `<tr><td>${curr.jrxTime}</td><td>${curr.jrxM}</td></tr>`;
        return pre;
      }, "");
      const description = info
        ? `<table class="cesium-infoBox-defaultTable"><tr><td>坐标</td><td>${jd},${wd},${gc}</td></tr><tr><td>监测时间</td><td>监测数值(米)</td></tr>${info}</table>`
        : undefined;
      addBillboard(position, {
        image: "assets/孔隙水压计.gif",
        description,
        name: jcsbSbbh,
      });
    });
  });
}

function loadGPS(position, data) {
  const { jcsbSbbh, jd, wd, gc } = data;
  fetch(`${gpsUrl}?gpsSbbh=${jcsbSbbh}`).then((res) => {
    res.json().then((gpsData) => {
      const gpsArray = gpsData.GPS;
      const info = gpsArray.reduce((pre, curr) => {
        pre += `<tr><td>${curr.gpsTime}</td><td>${curr.gpsx}</td><td>${curr.gpsy}</td><td>${curr.gpsz}</td></tr>`;
        return pre;
      }, "");
      const description = info
        ? `<table class="cesium-infoBox-defaultTable"><tr><td>坐标</td><td colspan=3>${jd},${wd},${gc}</td></tr><tr><td>监测时间</td><td>X值(mm)</td><td>Y值(mm)</td><td>Z值(mm)</td></tr>${info}</table>`
        : undefined;
      addBillboard(position, {
        image: "assets/位移计.gif",
        description,
        name: jcsbSbbh,
      });
    });
  });
}

function loadKSW(position, data) {
  const { jcsbSbbh, jd, wd, gc } = data;
  fetch(`${kswUrl}?kswSbbh=${jcsbSbbh}`).then((res) => {
    res.json().then((kswData) => {
      const kswArray = kswData.KSW;
      const info = kswArray.reduce((pre, curr) => {
        pre += `<tr><td>${curr.kswTime}</td><td>${curr.kswHbbg}</td></tr>`;
        return pre;
      }, "");
      const description = info
        ? `<table class="cesium-infoBox-defaultTable"><tr><td>坐标</td><td>${jd},${wd},${gc}</td></tr><tr><td>监测时间</td><td>监测数值(米)</td></tr>${info}</table>`
        : undefined;
      addBillboard(position, {
        image: "assets/水位计.gif",
        description,
        name: jcsbSbbh,
      });
    });
  });
}

function loadNBWY(position, data) {
  const { jcsbSbbh, jd, wd, gc } = data;
  fetch(`${nbwyUrl}?nbwySbbh=${jcsbSbbh}`).then((res) => {
    res.json().then((nbwyData) => {
      const nbwyArray = nbwyData.NBWY;
      const info = nbwyArray.reduce((pre, curr) => {
        pre += `<tr><td>${curr.nbwyTime}</td><td>${curr.nbwyWyz}</td></tr>`;
        return pre;
      }, "");
      const description = info
        ? `<table class="cesium-infoBox-defaultTable"><tr><td>坐标</td><td>${jd},${wd},${gc}</td></tr><tr><td>监测时间</td><td>监测数值(mm)</td></tr>${info}</table>`
        : undefined;
      addBillboard(position, {
        image: "assets/电子测斜仪.gif",
        description,
        name: jcsbSbbh,
      });
    });
  });
}

function loadYLJ(position, data) {
  const { jcsbSbbh, jd, wd, gc } = data;
  fetch(`${yljUrl}?ylSbbh=${jcsbSbbh}`).then((res) => {
    res.json().then((yljData) => {
      const yljArray = yljData.YL;
      const info = yljArray.reduce((pre, curr) => {
        pre += `<tr><td>${curr.ylTime}</td><td>${curr.ylYlz}</td></tr>`;
        return pre;
      }, "");
      const description = info
        ? `<table class="cesium-infoBox-defaultTable"><tr><td>坐标</td><td>${jd},${wd},${gc}</td></tr><tr><td>监测时间</td><td>监测数值(mm)</td></tr>${info}</table>`
        : undefined;
      addBillboard(position, {
        image: "assets/雨量计.gif",
        description,
        name: jcsbSbbh,
      });
    });
  });
}

/**
 * 添加标记
 * @param {Cesium.Cartographic} position 标记位置
 * @param {*} options
 * @param {String} options.image 图标
 * @param {String} options.description HTML字符串
 * @param {String} options.name 名称
 */
function addBillboard(position, options) {
  const { image = "assets/电子测斜仪.gif", description, name } = options;
  const billboard = new Cesium.Entity({
    position: Cesium.Cartographic.toCartesian(position),
    billboard: {
      image,
      width: 8, // default: undefined
      height: 26, // default: undefined
      //scaleByDistance: new Cesium.NearFarScalar(1.5e1, 2, 8.0e2, 0.5),
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
      disableDepthTestDistance: Number.POSITIVE_INFINITY,
      heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
    },
    point: {
      disableDepthTestDistance: Number.POSITIVE_INFINITY,
      color: Cesium.Color.CYAN,
      pixelSize: 1,
    },
    label: {
      text: name,
      disableDepthTestDistance: Number.POSITIVE_INFINITY,
      scaleByDistance: new Cesium.NearFarScalar(1.5e1, 1.5, 8.0e2, 0.0),
      verticalOrigin: Cesium.VerticalOrigin.TOP,
      heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
    },
    name,
    description,
  });
  viewer.entities.add(billboard);
}
